package middlewares

import (
	"gozeroSingle/utils"
	"net/http"

	sentinel "github.com/alibaba/sentinel-golang/api"
	"github.com/alibaba/sentinel-golang/core/base"
	"github.com/zeromicro/go-zero/rest/httpx"
)

/**
 * 限流
 *
 * @param http.HandlerFunc next ------------------------------必传
 * @return http.HandlerFunc
 * @author huwl
 */
func LimiterMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		e, b := sentinel.Entry(utils.LimiterResource, sentinel.WithResourceType(base.ResTypeWeb), sentinel.WithTrafficType(base.Inbound))
		if b != nil {
			httpx.WriteJsonCtx(r.Context(), w, 419, utils.ErrorOutput("人气太火爆了，请稍等"))
			return
		}

		e.Exit()
		next(w, r)
	}
}
